package com.example.orderedThread.syn;

public class OrderedThread extends Thread {
    private static final Object lock = new Object();
    private static int curNum = 1;
    private final int num;

    public OrderedThread(int num) {
        this.num = num;
    }

//    @Override
//    public void run() {
//        synchronized (lock) {
//            while (num != curNum) {
//                try {
//                    lock.wait();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//            System.out.println("线程" + num);
//            curNum++;
//            lock.notifyAll();
//        }
//    }

    @Override
    public void run() {
        synchronized (lock) {
            while (true) {
                if (num != curNum) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("线程" + num);
                    curNum++;
                    lock.notifyAll();
                    break;
                }
            }
        }
    }


    public static void main(String[] args) {
        OrderedThread thread1 = new OrderedThread(1);
        OrderedThread thread2 = new OrderedThread(2);
        OrderedThread thread3 = new OrderedThread(3);
        OrderedThread thread4 = new OrderedThread(4);
        OrderedThread thread5 = new OrderedThread(5);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}
